package com.wandian.weather.mvvm.weatheractivity;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.TimeFormate;
import com.mylib.libcore.utils.TimeUtils;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.weather.R;
import com.wandian.weather.adapter.WeatherFifteenDayAdapter;
import com.wandian.weather.bean.AqiBean;
import com.wandian.weather.bean.WeatherBean;
import com.wandian.weather.bean.WeatherInformationBean;
import com.wandian.weather.databinding.WeatherActivityHomeBinding;
import com.wandian.weather.tools.CalendarUtil;
import com.wandian.weather.tools.LunarCalendar;
import com.wandian.weather.tools.WeatherUtil;
import com.wandian.weather.view.WeatherViewOne;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import me.jessyan.autosize.utils.ScreenUtils;

/**
 * @author Administrator
 * @date 2019/12/16-13:30
 * @description 天气主页activity
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_WEATHER_HOME)
public class WeatherHomeActivity extends BaseMVVMActivity<WeatherHomeActivityViewModel> {

    private WeatherActivityHomeBinding dataBinding;
    private WeatherFifteenDayAdapter weatherFifteenDayAdapter;
    private String cityID;



    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.weather_activity_home);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) dataBinding.viewSys.getLayoutParams(); //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
        linearParams.height = ScreenUtils.getStatusBarHeight();;
        dataBinding.viewSys.setLayoutParams(linearParams);

        initRecycleFifteenDay();
        initClink();
        mViewModel.getWeatherData(getContext());
        initViewData();
    }


    private void initClink(){
        dataBinding.bindSysToolBar.toolBarIvBack.setOnClickListener(v -> {
            finish();
        });
        //天气头部
        dataBinding.layoutWeatherTop.llWeatherTop.setOnClickListener(v ->ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_REAL_WEATHER).navigation());
        //30天天气
        dataBinding.layout15Day.tv30Day.setOnClickListener(v ->{
            if(!UIUtils.isEmpty(cityID))ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_MORE_DAY_WEATHER).withString("cityID",cityID).navigation();
        });
        //更多天气
        dataBinding.bindSysToolBar.toolBarTitleRight.setOnClickListener(v ->{
            if(!UIUtils.isEmpty(cityID))ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_MORE_DAY_WEATHER).withString("cityID",cityID).navigation();
        });
    }

    /**
     * 15天天气recycleview
     */
    private void initRecycleFifteenDay(){
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        dataBinding.layout15Day.recycler15Day.setLayoutManager(layoutManager);
        weatherFifteenDayAdapter = new WeatherFifteenDayAdapter(R.layout.weather_item_style_list_15_days);
        dataBinding.layout15Day.recycler15Day.setAdapter(weatherFifteenDayAdapter);

        weatherFifteenDayAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_FIFTEEN_DAY_WEATHER).navigation();
            }
        });
    }

    private void initViewData(){
        dataBinding.bindSysToolBar.toolBarTitleRight.setText("更多天气");
        dataBinding.bindSysToolBar.toolBarTitleRight.setVisibility(View.VISIBLE);
        dataBinding.bindSysToolBar.toolBarTvTitle.setText("天气");
        mViewModel.weatherInformationBean.observe(this,weatherInformationBean -> {
            if(!UIUtils.isEmpty(weatherInformationBean)){
                if(!UIUtils.isEmpty( weatherInformationBean.getCity())) cityID = weatherInformationBean.getCity().getCityid();
              AppContext.getInstance().getAppPreferencesHelper().setKeyValue("WeatherInformationBean",JsonUtil.toJson(weatherInformationBean));
                if(!UIUtils.isEmpty(generate15dayData(weatherInformationBean))){
                    init24hourChartView(weatherInformationBean);
                    initNl(weatherInformationBean);
                    Log.d("generate15dayData",generate15dayData(weatherInformationBean).size()+"");
                    weatherFifteenDayAdapter.setNewData(generate15dayData(weatherInformationBean));
                }
            }
        });
    }

    /**
     * 15天天气数据
     * @return
     */
    private List<WeatherBean> generate15dayData(WeatherInformationBean weatherInformationBean) {
        List<WeatherBean> list = new ArrayList<>();
        try {
            if(!UIUtils.isEmpty(weatherInformationBean.getYesterday())){
                WeatherInformationBean.YesterdayBean yesterdayBean = weatherInformationBean.getYesterday();
                if(!UIUtils.isEmpty(yesterdayBean)){
                    WeatherBean model = new WeatherBean();
                    model.setWeek("昨天");
                    String date = TimeUtils.timeStringToTimeString(yesterdayBean.getDate(), "MM月dd日", "MM/dd");
                    model.setDate(date);
                    model.setDayTemp(Integer.parseInt(yesterdayBean.getHtemp()));
                    model.setNightTemp(Integer.parseInt(yesterdayBean.getLtemp()));
                    model.setDayWeather(yesterdayBean.getWeather());
                    model.setNightWeather(yesterdayBean.getWeather_night());
                    model.setWindOrientation(yesterdayBean.getWD());

                    AqiBean aqiBean = WeatherUtil.getAqiBean(getContext(), Integer.parseInt(yesterdayBean.getAqi()));
                    model.setAqiBean(aqiBean);

                    model.setWindLevel(yesterdayBean.getWS());
//                    model.setDayPic(WeatherUtil.getWeatherStateImage(yesterdayBean.getImg_num(), 48));
//                    model.setNightPic(WeatherUtil.getWeatherStateImage(yesterdayBean.getImg_num(), true,48));
                    list.add(model);
                }
            }
            for (int i = 0; i < weatherInformationBean.getWeather30().size(); i++) {
                if(i<15){
                    Log.d("generate15dayData", "111111");
                    WeatherInformationBean.Weather30Bean weather30Bean = weatherInformationBean.getWeather30().get(i);
                    WeatherBean model = new WeatherBean();
                    if (i == 0) {
                        model.setWeek("今天");
                    } else if (i == 1) {
                        model.setWeek("明天");
                    } else {
                        model.setWeek(weather30Bean.getWeek().replace("星期", "周"));
                    }
                    String date = TimeUtils.timeStringToTimeString(weather30Bean.getDate(), "MM月dd日", "MM/dd");
                    model.setDate(date);
                    model.setDayTemp(Integer.parseInt(weather30Bean.getHtemp()));
                    model.setNightTemp(Integer.parseInt(weather30Bean.getLtemp()));

                    if(!UIUtils.isEmpty(weather30Bean.getWeather_day())){
                        model.setDayWeather(weather30Bean.getWeather_day());
                    }else {
                        model.setDayWeather(weather30Bean.getWeather());
                    }
                    model.setNightWeather(weather30Bean.getWeather_night());
                    model.setWindOrientation(weather30Bean.getWD());

                    AqiBean aqiBean = WeatherUtil.getAqiBean(getContext(), Integer.parseInt(weather30Bean.getAqi()));
                    model.setAqiBean(aqiBean);
                    list.add(model);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 农历
     * @return
     */
    private void initNl(WeatherInformationBean weatherInformationBean) {
        try {
            if (weatherInformationBean != null) {
                WeatherInformationBean.NlBean nlBean = weatherInformationBean.getNl();
                String date = TimeFormate.timeStringToTimeString(nlBean.getDate(), "yyyyMMdd", "MM月dd日");
                String week = nlBean.getMore().getWeek();
                dataBinding.itemNlTitle.tvNlDateWeek.setText(week);
                dataBinding.itemNlTitle.tvNlDate.setText(date);

                TextView[] tvJis = new TextView[]{dataBinding.itemNl.tvJi1, dataBinding.itemNl.tvJi2, dataBinding.itemNl.tvJi3, dataBinding.itemNl.tvJi4, dataBinding.itemNl.tvJi5, dataBinding.itemNl.tvJi6};
                TextView[] tvYis = new TextView[]{dataBinding.itemNl.tvYi1, dataBinding.itemNl.tvYi2, dataBinding.itemNl.tvYi3, dataBinding.itemNl.tvYi4, dataBinding.itemNl.tvYi5, dataBinding.itemNl.tvYi6};

                String[] strYis = nlBean.getMore().getY().split(" ");
                String[] strJis = nlBean.getMore().getJ().split(" ");

                int tagJi = strJis.length >= 6 ? 6 : strJis.length;
                for (int i = 0; i < tagJi; i++) {
                    tvJis[i].setVisibility(View.VISIBLE);
                    tvJis[i].setText(strJis[i]);
                }

                int tagYi = strYis.length >= 6 ? 6 : strYis.length;
                for (int i = 0; i < tagYi; i++) {
                    tvYis[i].setVisibility(View.VISIBLE);
                    tvYis[i].setText(strYis[i]);
                }
//
//                llNlroot.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        MobclickAgent.onEvent(mActivity, "weather_calendar_enter.click");
//                        ARouter.getInstance().build("/ui/CalendarActivity").navigation();
//                    }
//                });

                Calendar calDay = Calendar.getInstance();
                dataBinding.itemNlTitle.tvOldLunar.setText(nlBean.getBase().getMonth_text()+nlBean.getBase().getDay_text());

                LunarCalendar lunarCalendar = new LunarCalendar();
                CalendarUtil util = new CalendarUtil(calDay);
                HashMap<String, Object> map = lunarCalendar.getBaseInfo(calDay.get(Calendar.YEAR), (calDay.get(Calendar.MONTH) + 1), calDay.get(Calendar.DATE));
                String jsonString = JsonUtil.toJson(map);
                JSONObject jsonObject =new JSONObject(jsonString);

                String oldMonth = jsonObject.getJSONObject("oldtime").getString("month");
                String oldDay = jsonObject.getJSONObject("oldtime").getString("day");
                int week1 = calDay.get(Calendar.WEEK_OF_YEAR);
                String weekNum = "第" + week1 + "周";
                String descOldLunar = weekNum + "  " + util.cyclical() + "[" + util.animalsYear() + "]年 " + oldMonth + "月  "
                        + oldDay + "日";
                dataBinding.itemNlTitle.tvDescOldLunar.setText(descOldLunar);

                dataBinding.itemNlTitle.tvJiejiari.setText(weatherInformationBean.getWeather30().get(0).getNl().getJr());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 24小时天气折线图
     * @return
     */
    private void init24hourChartView(WeatherInformationBean weatherInformationBean) {


        //画曲线(已修复不圆滑问题)
        dataBinding.layout24Hour.weatherViewOne.setLineType(WeatherViewOne.LINE_TYPE_DISCOUNT);

        //设置线宽
        dataBinding.layout24Hour.weatherViewOne.setLineWidth(2f);

        //设置白天和晚上线条的颜色
        dataBinding.layout24Hour.weatherViewOne.setDayLineColor(Color.parseColor("#2FDC94"));

        //填充天气数据
        dataBinding.layout24Hour.weatherViewOne.setList(generateHourData(weatherInformationBean),false);
        if (Build.VERSION.SDK_INT >= 22){
            dataBinding.layout24Hour.weatherViewOne.setNestedScrollingEnabled(false);
        }
        dataBinding.layout24Hour.weatherViewOne.post(new Runnable() {
            @Override
            public void run() {
                dataBinding.layout24Hour.weatherViewOne.invalidate();
            }
        });

    }

    /**
     * 24小时天气数据
     * @return
     */
    private List<WeatherBean> generateHourData( WeatherInformationBean weatherInformationBean) {
        List<WeatherBean> list = new ArrayList<>();
        try {
            for (WeatherInformationBean.Hour24Bean hour24Bean : weatherInformationBean.getHour24()) {
                WeatherBean model = new WeatherBean();
                model.setDate(hour24Bean.getDatetime());
                model.setDayWeather(hour24Bean.getWeather() + "");
                model.setWeek(hour24Bean.getHour());
                model.setDayTemp(Integer.parseInt(hour24Bean.getStemp()));

                AqiBean aqiBean = WeatherUtil.getAqiBean(getContext(), Integer.parseInt(hour24Bean.getAqi()));
                model.setNightWeather(aqiBean.getAqiName());
                model.setWindLevel(hour24Bean.getWS());
                model.setAqiBean(aqiBean);
//                model.setDayPic(WeatherUtil.getWeatherStateImage(hour24Bean.getImg_num(), 48));
//                model.setNightPic(WeatherUtil.getWeatherStateImage(hour24Bean.getImg_num(), true,48));
                model.setWindOrientation(hour24Bean.getWD());
                list.add(model);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}
